<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="简述23中设计模式">
<meta name="keywords" content="设计模式">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式">
<meta property="og:url" content="http://yoursite.com/design/design/设计模式/index.html">
<meta property="og:site_name" content="我的云笔记">
<meta property="og:description" content="简述23中设计模式">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/blog/images/ProxyPattern.png">
<meta property="og:image" content="http://yoursite.com/blog/images/DecoratorPattern.png">
<meta property="og:image" content="http://yoursite.com/blog/images/Bridge.png">
<meta property="og:image" content="http://yoursite.com/blog/images/observer.png">
<meta property="og:image" content="http://yoursite.com/blog/images/20170422200327160.png">
<meta property="og:updated_time" content="2018-08-15T07:45:42.222Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="设计模式">
<meta name="twitter:description" content="简述23中设计模式">
<meta name="twitter:image" content="http://yoursite.com/blog/images/ProxyPattern.png">






  <link rel="canonical" href="http://yoursite.com/design/design/设计模式/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>设计模式 | 我的云笔记</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?5102824f4157d2cbdb282a1a889d910e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的云笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/design/design/设计模式/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的云笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">设计模式
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-07-29 10:27:11" itemprop="dateCreated datePublished" datetime="2018-07-29T10:27:11+08:00">2018-07-29</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-08-15 15:45:42" itemprop="dateModified" datetime="2018-08-15T15:45:42+08:00">2018-08-15</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/design/" itemprop="url" rel="index"><span itemprop="name">design</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/blog/design/design/设计模式/" class="leancloud_visitors" data-flag-title="设计模式">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>简述23中设计模式</p>
<a id="more"></a>
<h1 id="六大原则"><a href="#六大原则" class="headerlink" title="六大原则"></a>六大原则</h1><h2 id="单一职责原则"><a href="#单一职责原则" class="headerlink" title="单一职责原则"></a>单一职责原则</h2><p>类的功能尽量做到单一</p>
<h2 id="里氏替换原则"><a href="#里氏替换原则" class="headerlink" title="里氏替换原则"></a>里氏替换原则</h2><p>一个子类应该可以替换掉父类并且可以正常工作  </p>
<h2 id="接口隔离原则"><a href="#接口隔离原则" class="headerlink" title="接口隔离原则"></a>接口隔离原则</h2><p>一个接口拥有的行为应该尽可能的小 </p>
<h2 id="依赖倒置原则"><a href="#依赖倒置原则" class="headerlink" title="依赖倒置原则"></a>依赖倒置原则</h2><p>高层模块不该依赖于低层模块，二者都应该依赖于抽象，抽象不应该依赖于细节，细节应该依赖于抽象 </p>
<h2 id="迪米特原则"><a href="#迪米特原则" class="headerlink" title="迪米特原则"></a>迪米特原则</h2><p>一个类应该尽量不要知道其他类太多的东西 </p>
<h2 id="开-闭原则"><a href="#开-闭原则" class="headerlink" title="开-闭原则"></a>开-闭原则</h2><p>对修改关闭，对扩展开放</p>
<h1 id="创建型"><a href="#创建型" class="headerlink" title="创建型"></a>创建型</h1><h2 id="1-单例"><a href="#1-单例" class="headerlink" title="1. 单例"></a>1. 单例</h2><h3 id="错误实现"><a href="#错误实现" class="headerlink" title="错误实现"></a>错误实现</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton singleton;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (singleton == <span class="keyword">null</span>) &#123;<span class="comment">//多线程情况下这里判断会失效</span></span><br><span class="line">            singleton = <span class="keyword">new</span> Singleton();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> singleton;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同步方法有性能问题，同步范围太小又会造成多次new</p>
<h3 id="double-check"><a href="#double-check" class="headerlink" title="double check"></a>double check</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (instance != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> instance;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">			<span class="keyword">if</span> (instance == <span class="keyword">null</span>) &#123;</span><br><span class="line">				instance = <span class="keyword">new</span> Singleton();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> instance;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>避免的上面方式的明显缺点，但是java内存模型（jmm）并不限制处理器重排序，在执行instance=new Singleton()；时，并不是原子语句，实际是包括了下面三大步骤：</p>
<p>1.为对象分配内存</p>
<p>2.初始化实例对象</p>
<p>3.把引用instance指向分配的内存空间</p>
<p>这个三个步骤并不能保证按序执行，处理器会进行指令重排序优化，存在这样的情况：优化重排后执行顺序为：1,3,2, 这样在线程1执行到3时，instance已经不为null了，线程2此时判断instance!=null，则直接返回instance引用，但现在实例对象还没有初始化完毕，此时线程2使用instance可能会造成程序崩溃。 </p>
<h3 id="volatile作用"><a href="#volatile作用" class="headerlink" title="volatile作用"></a>volatile作用</h3><p>1.保证可见性</p>
<p><strong>可以保证在多线程环境下，变量的修改可见性</strong>。每个线程都会在工作内存（类似于寄存器和高速缓存），实例对象都存放在主内存中，在每个线程要使用的时候把主内存中的内容拷贝到线程的工作内存中。使用volatile关键字修饰后的变量，保证每次修改了变量需要立即写回主内存中，同时通知所有的该对变量的缓存失效，保证缓存一致性，其他线程需要使用该共享变量时就要重新从住内存中获取最新的内容拷贝到工作内存中供处理器使用。这样就可以保证变量修改的可见性了。但volatile不能保证原子性，比如++操作。</p>
<p><strong>2.提供内存屏障</strong></p>
<p>volatile关键字能够通过提供内存屏障，来保证某些指令顺序处理器不能够优化重排，编译器在生成字节码时，会在指令序列中插入内存屏障来禁止特定类型的处理器重排序。</p>
<p>下面是保守策略插入内存屏障：</p>
<ul>
<li><p>在每个volatile写操作的前面插入一个StoreStore屏障。</p>
</li>
<li><p>在每个volatile写操作的后面插入一个StoreLoad屏障。</p>
</li>
<li><p>在每个volatile读操作的前面插入一个LoadLoad屏障。</p>
</li>
<li><p>在每个volatile读操作的后面插入一个LoadLoad屏障。</p>
</li>
</ul>
<p>这样可以保证在volatile关键字修饰的变量的赋值和读取操作前后两边的大的顺序不会改变，在内存屏障前面的顺序可以交换，屏障后面的也可以换序，但是不能跨越内存屏障重排执行顺序。</p>
<h3 id="静态内部类"><a href="#静态内部类" class="headerlink" title="静态内部类"></a>静态内部类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> InstanceHolder.instance;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">InstanceHolder</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> <span class="keyword">static</span> Singleton instance = <span class="keyword">new</span> Singleton();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="恶汉模式"><a href="#恶汉模式" class="headerlink" title="恶汉模式"></a>恶汉模式</h3><p>只要类加载了就会执行</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Singleton instance = <span class="keyword">new</span> Singleton();</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> instance;</span><br><span class="line">	&#125;	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="2-静态工厂方法"><a href="#2-静态工厂方法" class="headerlink" title="2. 静态工厂方法"></a>2. 静态工厂方法</h2><p>​    一个工厂类，一个产品接口（其实也可以是一个抽象类，甚至一个普通的父类，但通常我们觉得接口是最稳定的，所以基本不需要考虑普通父类的情况），和一群实现了产品接口的具体产品，而这个工厂类，根据传入的参数去创造一个具体的实现类，并向上转型为接口作为结果返回。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticFactory</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Map <span class="title">getMap</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="string">"HashMap"</span>.equals(name)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">new</span> HashMap();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (<span class="string">"TreeMap"</span>.equals(name)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">new</span> TreeMap();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (<span class="string">"LinkedHashMap"</span>.equals(name)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">new</span> LinkedHashMap();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (<span class="string">"hashMap"</span>.equals(name)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">new</span> HashMap();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-工厂方法"><a href="#3-工厂方法" class="headerlink" title="3. 工厂方法"></a>3. 工厂方法</h2><p>产品的生产延迟到具体工厂实现类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FactoryMethod</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Factory</span> </span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> Product <span class="title">createProduct</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Product</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Factory f1=()-&gt;()-&gt;System.out.println(<span class="string">"product1"</span>);</span><br><span class="line">		Factory f2=()-&gt;()-&gt;System.out.println(<span class="string">"product2"</span>);</span><br><span class="line">	</span><br><span class="line">		</span><br><span class="line">		f1.createProduct().doSomething();</span><br><span class="line">		f2.createProduct().doSomething();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-抽象工厂"><a href="#4-抽象工厂" class="headerlink" title="4. 抽象工厂"></a>4. 抽象工厂</h2><p>抽象工厂只是把工厂的一个方法变成多个</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Factory</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> Product <span class="title">createProduct1</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Product <span class="title">createProduct2</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Product <span class="title">createProduct3</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="5-建造者模式"><a href="#5-建造者模式" class="headerlink" title="5. 建造者模式"></a>5. 建造者模式</h2><p>构造对象极其复杂，并且需要按照特定步骤，但过程又过程又比较类似。</p>
<p>客户端不需要知道产品怎么造出来的，要新增产品只要新增builder就行了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Builder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">		<span class="keyword">public</span> String name;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">int</span> age;</span><br><span class="line">		<span class="keyword">public</span> Date birthday;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">PersonBuilder</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step1</span><span class="params">()</span></span>;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step2</span><span class="params">()</span></span>;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step3</span><span class="params">()</span></span>;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> Person <span class="title">get</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">BuilderManager</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Person <span class="title">build</span><span class="params">(PersonBuilder builder)</span></span>&#123;</span><br><span class="line">			builder.step1();</span><br><span class="line">			builder.step2();</span><br><span class="line">			builder.step3();</span><br><span class="line">			<span class="keyword">return</span> builder.get();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		PersonBuilder b1=<span class="keyword">new</span> PersonBuilder() &#123;</span><br><span class="line">			<span class="keyword">private</span> Person p=<span class="keyword">new</span> Person();</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				p.birthday=<span class="keyword">new</span> Date();</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				p.age=<span class="number">2</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				p.name=<span class="string">"p1"</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> Person <span class="title">get</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				<span class="keyword">return</span> p;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		PersonBuilder b2=<span class="keyword">new</span> PersonBuilder() &#123;</span><br><span class="line">			<span class="keyword">private</span> Person p=<span class="keyword">new</span> Person();</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				p.birthday=<span class="keyword">new</span> Date(<span class="number">0</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				p.age=<span class="number">22</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				p.name=<span class="string">"p2"</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> Person <span class="title">get</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				<span class="keyword">return</span> p;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		</span><br><span class="line">		Person p1=BuilderManager.build(b1);</span><br><span class="line">		Person p2=BuilderManager.build(b2);</span><br><span class="line">		System.out.println(p1.name);</span><br><span class="line">		System.out.println(p2.name);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="6-原型模式"><a href="#6-原型模式" class="headerlink" title="6. 原型模式"></a>6. 原型模式</h2><p>浅复制只复制引用，深复制复制所有属性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Clone</span> </span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> MyBean BEAN = create();</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> String name = getName(<span class="number">10000000</span>);</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> String name2=name+<span class="string">"1"</span>;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> String name3=name+<span class="string">"2"</span>;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> String name4=name+<span class="string">"3"</span>;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ClassNotFoundException, InterruptedException </span>&#123;</span><br><span class="line">		Class.forName(Clone.class.getName());</span><br><span class="line"></span><br><span class="line">		ExecResult r = <span class="keyword">null</span>;</span><br><span class="line">		MultiThreadResult r2 = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">int</span> count=<span class="number">100000</span>;</span><br><span class="line">		</span><br><span class="line">		r = MultiThreadTest.calculate(<span class="string">"clone"</span>, Clone::doClone, <span class="number">100</span>,count);</span><br><span class="line">		System.out.println(r.getResult());</span><br><span class="line">		r2 = MultiThreadTest.getResult(Clone::doClone, <span class="number">10000</span>);</span><br><span class="line">		System.out.println(r2.getResult());</span><br><span class="line"></span><br><span class="line">		r = MultiThreadTest.calculate(<span class="string">"deepClone"</span>, Clone::deepClone, <span class="number">100</span>,count);</span><br><span class="line">		System.out.println(r.getResult());</span><br><span class="line">		r2 = MultiThreadTest.getResult(Clone::deepClone, <span class="number">10000</span>);</span><br><span class="line">		System.out.println(r2.getResult());</span><br><span class="line"></span><br><span class="line">		r = MultiThreadTest.calculate(<span class="string">"create"</span>, Clone::create, <span class="number">100</span>,count);</span><br><span class="line">		System.out.println(r.getResult());</span><br><span class="line">		r2 = MultiThreadTest.getResult(Clone::create, <span class="number">10000</span>);</span><br><span class="line">		System.out.println(r2.getResult());</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title">getName</span><span class="params">(<span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">		StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; length; i++) &#123;</span><br><span class="line">			sb.append(<span class="string">"1"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		System.out.println(<span class="string">"创建了一个长达"</span> + sb.length() + <span class="string">"的字符串"</span>);</span><br><span class="line">		<span class="keyword">return</span> sb.toString();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MyBean <span class="title">create</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		MyBean bean = <span class="keyword">new</span> MyBean();</span><br><span class="line">		bean.setName1(name);</span><br><span class="line">		bean.setName2(name2);</span><br><span class="line">		bean.setName3(name3);</span><br><span class="line">		bean.setName4(name4);</span><br><span class="line">		</span><br><span class="line">		MyBean son=<span class="keyword">new</span> MyBean();</span><br><span class="line">		son.setName1(name);</span><br><span class="line">		son.setName1(name2);</span><br><span class="line">		son.setName1(name3);</span><br><span class="line">		</span><br><span class="line">		bean.setSon(son);</span><br><span class="line">		<span class="keyword">return</span> bean;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MyBean <span class="title">doClone</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> BEAN.clone();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">deepClone</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			ByteArrayOutputStream bo = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">			ObjectOutputStream oo = <span class="keyword">new</span> ObjectOutputStream(bo);</span><br><span class="line">			oo.writeObject(BEAN);</span><br><span class="line">			ByteArrayInputStream bi = <span class="keyword">new</span> ByteArrayInputStream(bo.toByteArray());</span><br><span class="line">			ObjectInputStream oi = <span class="keyword">new</span> ObjectInputStream(bi);</span><br><span class="line">			oi.read();</span><br><span class="line">		&#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(ex);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从log来看，深复制只是在单线程的情况下性能有点问题，其它的都差不多</p>
<figure class="highlight verilog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">---------clone-------------</span><br><span class="line">执行<span class="number">100</span>次:<span class="number">0</span><span class="variable">.0408</span>(ms)</span><br><span class="line">执行<span class="number">100</span>,<span class="number">000</span>次:<span class="number">4</span><span class="variable">.6025</span>(ms)</span><br><span class="line"></span><br><span class="line"><span class="number">10000</span>个线程,创建耗时:<span class="number">15</span><span class="variable">.5978</span>(ms),执行耗时:<span class="number">673</span><span class="variable">.3472</span>(ms),平均耗时<span class="number">0</span><span class="variable">.0421</span>(ms)</span><br><span class="line">---------deepClone-------------</span><br><span class="line">执行<span class="number">100</span>次:<span class="number">15</span><span class="variable">.8698</span>(ms)</span><br><span class="line">执行<span class="number">100</span>,<span class="number">000</span>次:<span class="number">413</span><span class="variable">.6056</span>(ms)</span><br><span class="line"></span><br><span class="line"><span class="number">10000</span>个线程,创建耗时:<span class="number">10</span><span class="variable">.8982</span>(ms),执行耗时:<span class="number">659</span><span class="variable">.5116</span>(ms),平均耗时<span class="number">0</span><span class="variable">.0583</span>(ms)</span><br><span class="line">---------create-------------</span><br><span class="line">执行<span class="number">100</span>次:<span class="number">0</span><span class="variable">.0718</span>(ms)</span><br><span class="line">执行<span class="number">100</span>,<span class="number">000</span>次:<span class="number">3</span><span class="variable">.9428</span>(ms)</span><br><span class="line"></span><br><span class="line"><span class="number">10000</span>个线程,创建耗时:<span class="number">7</span><span class="variable">.4955</span>(ms),执行耗时:<span class="number">628</span><span class="variable">.8875</span>(ms),平均耗时<span class="number">0</span><span class="variable">.0306</span>(ms)</span><br></pre></td></tr></table></figure>
<h1 id="结构型"><a href="#结构型" class="headerlink" title="结构型"></a>结构型</h1><h2 id="7-代理模式"><a href="#7-代理模式" class="headerlink" title="7. 代理模式"></a>7. 代理模式</h2><p>改变原有方法的某些行为，参考<a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop" target="_blank" rel="noopener">spring aop</a></p>
<p>cglib动态代理，通过MethodInterceptor拦截原有方法</p>
<p><img src="/blog/images\ProxyPattern.png" alt="img"> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.cglib.proxy.Enhancer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cglib.proxy.LazyLoader;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cglib.proxy.MethodInterceptor;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MockUtil</span></span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">mock</span><span class="params">(Class&lt;T&gt; clazz,MethodInterceptor callback)</span></span>&#123;</span><br><span class="line">		Enhancer e=<span class="keyword">new</span> Enhancer();</span><br><span class="line">		e.setSuperclass(clazz);</span><br><span class="line">		e.setCallback(callback);</span><br><span class="line">		<span class="keyword">return</span> (T)e.create();</span><br><span class="line">	&#125;	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="8-适配器"><a href="#8-适配器" class="headerlink" title="8. 适配器"></a>8. 适配器</h2><p>扩展类功能用于适配特定接口，实现一个可以在thread里执行的map</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Adapter</span> </span>&#123;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RunableMap</span> <span class="keyword">extends</span> <span class="title">HashMap</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			System.out.println(<span class="keyword">this</span>.keySet());</span><br><span class="line">		&#125;		</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">		RunableMap map=<span class="keyword">new</span> RunableMap();</span><br><span class="line">		map.put(<span class="string">"1"</span>, <span class="string">"1"</span>);</span><br><span class="line">		map.put(<span class="string">"2"</span>, <span class="string">"1"</span>);</span><br><span class="line">		map.put(<span class="string">"3"</span>, <span class="string">"1"</span>);</span><br><span class="line">		map.put(<span class="string">"4"</span>, <span class="string">"1"</span>);</span><br><span class="line">		<span class="keyword">new</span> Thread(map).start();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="9-装饰器"><a href="#9-装饰器" class="headerlink" title="9. 装饰器"></a>9. 装饰器</h2><p>给类动态添加方法，例如给HttpServletRequest添加setParam</p>
<p>使用适配器要求接口不变，而且要用新增的方法有需要知道实际的实现类，所以用的场景不大</p>
<p><img src="/blog/images\DecoratorPattern.png" alt="Decorator pattern class diagram"> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Decorator</span> </span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span></span>;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sleep</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultPerson</span> <span class="keyword">implements</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			System.out.println(<span class="string">"hello"</span>);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sleep</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			System.out.println(<span class="string">"zzzzzz"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PersonDecorator</span> <span class="keyword">implements</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> Person person;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">PersonDecorator</span><span class="params">(Person person)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.person=person;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			person.say();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sleep</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			person.sleep();			</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			System.out.println(<span class="string">"running"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Person p=<span class="keyword">new</span> PersonDecorator(<span class="keyword">new</span> DefaultPerson());</span><br><span class="line"></span><br><span class="line">		PersonDecorator dp=(PersonDecorator)p;</span><br><span class="line">		dp.run();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="10-桥接模式"><a href="#10-桥接模式" class="headerlink" title="10.桥接模式"></a>10.桥接模式</h2><p>将一部分要变化的内容抽象出来，主要执行类不变，当需要执行不同操作时，放入不同的implement</p>
<p>汽车要换 变速器 只需要传入不同的Transmission</p>
<p><img src="/blog/images\Bridge.png" alt="Bridge pattern class diagram"> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bridge</span> </span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Impl</span> </span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doMethod</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Holder</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> Impl impl;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setImpl</span><span class="params">(Impl impl)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.impl = impl;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">operation</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			impl.doMethod();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Impl impl1=()-&gt;System.out.println(<span class="string">"impl1"</span>);</span><br><span class="line">		Impl impl2=()-&gt;System.out.println(<span class="string">"impl2"</span>);</span><br><span class="line">		</span><br><span class="line">		Holder h=<span class="keyword">new</span> Holder();</span><br><span class="line">		h.setImpl(impl1);</span><br><span class="line">		h.operation();</span><br><span class="line">		</span><br><span class="line">		h.setImpl(impl2);</span><br><span class="line">		h.operation();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="11-组合模式"><a href="#11-组合模式" class="headerlink" title="11. 组合模式"></a>11. 组合模式</h2><p>不用看了，就是一棵树</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Composite</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span> </span>&#123;</span><br><span class="line">		List&lt;TreeNode&gt; children;</span><br><span class="line">		String id;</span><br><span class="line">		String name;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="12-享元"><a href="#12-享元" class="headerlink" title="12. 享元"></a>12. 享元</h2><p>系统中存在一些可以用key区分的相似对象，主要用在于节约内存</p>
<p>WPF的属性系统是我看到对享元模式最好的使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Flyweight</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FlyweightFactory</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String,Flyweight&gt; map = <span class="keyword">new</span> ConcurrentHashMap();</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span>  <span class="keyword">static</span> Flyweight <span class="title">getFlyweight</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">			Flyweight f=map.get(key);</span><br><span class="line">			<span class="keyword">if</span>(f==<span class="keyword">null</span>) &#123;</span><br><span class="line">				f=<span class="keyword">new</span> Flyweight();</span><br><span class="line">				map.put(key, f);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> f;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="13-门面模式"><a href="#13-门面模式" class="headerlink" title="13. 门面模式"></a>13. 门面模式</h2><p>对外提供一个统一访问接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Facade</span> </span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassA</span> </span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassB</span> </span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassC</span> </span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassFacade</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> ClassA a=<span class="keyword">new</span> ClassA();</span><br><span class="line">		<span class="keyword">private</span> ClassB b=<span class="keyword">new</span> ClassB();</span><br><span class="line">		<span class="keyword">private</span> ClassC c=<span class="keyword">new</span> ClassC();</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invokeA</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			a.doSomething();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invokeB</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			b.doSomething();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invokeC</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			c.doSomething();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="行为型"><a href="#行为型" class="headerlink" title="行为型"></a>行为型</h1><h2 id="14-观察者"><a href="#14-观察者" class="headerlink" title="14. 观察者"></a>14. 观察者</h2><p>发布/订阅，生产/消费</p>
<p><img src="/blog/images\observer.png" alt="Observer pattern class diagram"> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Observer</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Observe</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(Observable ob)</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Observable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">		List&lt;Observe&gt; observers = <span class="keyword">new</span> ArrayList&lt;Observe&gt;();</span><br><span class="line">		<span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addObserver</span><span class="params">(Observe o)</span> </span>&#123;</span><br><span class="line">			observers.add(o);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">changed</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			name=name+<span class="string">"changed"</span>;</span><br><span class="line">			notifyObservers();<span class="comment">// 通知观察自己的所有观察者</span></span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">notifyObservers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			<span class="keyword">for</span> (Observe observer : observers) &#123;</span><br><span class="line">				observer.update(<span class="keyword">this</span>);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Observable ob=<span class="keyword">new</span> Observable();</span><br><span class="line">		ob.name=<span class="string">"被观察者"</span>;</span><br><span class="line">		</span><br><span class="line">		ob.addObserver(oo-&gt;System.out.println(<span class="string">"a看到了:"</span>+oo.name));</span><br><span class="line">		ob.addObserver(oo-&gt;System.out.println(<span class="string">"b看到了:"</span>+oo.name));</span><br><span class="line">		</span><br><span class="line">		ob.changed();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="15-模板方法"><a href="#15-模板方法" class="headerlink" title="15. 模板方法"></a>15. 模板方法</h2><p>模板规定好所有要做到事和步骤，具体类继承后实现或改变其中部分行为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TemplateMethod</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invoke</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.step1();</span><br><span class="line">		<span class="keyword">this</span>.step2();</span><br><span class="line">		<span class="keyword">this</span>.step3();</span><br><span class="line">		<span class="keyword">this</span>.step4();</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	 <span class="function"><span class="keyword">void</span> <span class="title">step1</span><span class="params">()</span> </span>&#123;&#125;; </span><br><span class="line">	 <span class="function"><span class="keyword">void</span> <span class="title">step2</span><span class="params">()</span> </span>&#123;&#125;;</span><br><span class="line">	 <span class="function"><span class="keyword">void</span> <span class="title">step3</span><span class="params">()</span> </span>&#123;&#125;;</span><br><span class="line">	 <span class="function"><span class="keyword">void</span> <span class="title">step4</span><span class="params">()</span> </span>&#123;&#125;;</span><br><span class="line">	</span><br><span class="line">	 <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Implement</span> <span class="keyword">extends</span> <span class="title">TemplateMethod</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">step3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			System.out.println(<span class="string">"步骤3要做到事情是。。。"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		TemplateMethod method=<span class="keyword">new</span> Implement();</span><br><span class="line">		method.invoke();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="16-命令模式"><a href="#16-命令模式" class="headerlink" title="16. 命令模式"></a>16. 命令模式</h2><p>将要做的工作封装在一个类里面</p>
<p>发送方只管发命令，命令谁执行，怎么执行不用管</p>
<p>可以和观察者模式结合，将观察者update方法的参数封装成一个命令，就实现事件驱动了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Command</span> </span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Invoker</span></span>&#123;</span><br><span class="line">		<span class="keyword">private</span> Manager manager;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pushCommand</span><span class="params">(Cmd cmd)</span> </span>&#123;</span><br><span class="line">			manager.comds.add(cmd);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Manager</span></span>&#123;</span><br><span class="line">		List&lt;Cmd&gt; comds=<span class="keyword">new</span> ArrayList();</span><br><span class="line">		<span class="keyword">private</span> Employer employer;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">assign</span><span class="params">()</span></span>&#123;</span><br><span class="line">			Cmd cmd=comds.remove(<span class="number">0</span>);</span><br><span class="line">			employer.doCommand(cmd);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Employer</span></span>&#123;</span><br><span class="line">		String name;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doCommand</span><span class="params">(Cmd cmd)</span> </span>&#123;</span><br><span class="line">			System.out.println(name+<span class="string">"开始工作"</span>);</span><br><span class="line">			cmd.run();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Cmd</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Cmd cmd1=()-&gt;System.out.println(<span class="string">"cmd1"</span>);</span><br><span class="line">		Cmd cmd2=()-&gt;System.out.println(<span class="string">"cmd2"</span>);</span><br><span class="line">		Cmd cmd3=()-&gt;System.out.println(<span class="string">"cmd3"</span>);</span><br><span class="line">		</span><br><span class="line">		Manager mg=<span class="keyword">new</span> Manager();</span><br><span class="line">		mg.employer=<span class="keyword">new</span> Employer();</span><br><span class="line">		mg.employer.name=<span class="string">"员工A"</span>;</span><br><span class="line">		</span><br><span class="line">		Invoker i=<span class="keyword">new</span> Invoker();</span><br><span class="line">		i.manager=mg;</span><br><span class="line">		i.pushCommand(cmd1);</span><br><span class="line">		i.pushCommand(cmd2);</span><br><span class="line">		i.pushCommand(cmd3);</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		mg.assign();</span><br><span class="line">		mg.assign();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="18-状态"><a href="#18-状态" class="headerlink" title="18. 状态"></a>18. 状态</h2><p>根据状态不同，行为也不同</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">State</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">		Stat st;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">			System.out.println(st.getWord(word));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="keyword">enum</span> Stat&#123;</span><br><span class="line">		a(<span class="number">1</span>),b(<span class="number">2</span>),c(<span class="number">3</span>);</span><br><span class="line">		<span class="keyword">int</span> count;</span><br><span class="line">		Stat(<span class="keyword">int</span> count) &#123;</span><br><span class="line">			<span class="keyword">this</span>.count=count;</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		<span class="function"><span class="keyword">public</span> String <span class="title">getWord</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">			StringBuilder sb=<span class="keyword">new</span> StringBuilder();</span><br><span class="line">			<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;count;i++) &#123;</span><br><span class="line">				sb.append(word+<span class="string">","</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> sb.toString();</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Person p=<span class="keyword">new</span> Person();</span><br><span class="line">		p.st=Stat.a;</span><br><span class="line">		p.say(<span class="string">"hello"</span>);</span><br><span class="line">		</span><br><span class="line">		p.st=Stat.b;</span><br><span class="line">		p.say(<span class="string">"hello"</span>);</span><br><span class="line">		</span><br><span class="line">		p.st=Stat.c;</span><br><span class="line">		p.say(<span class="string">"hello"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="19-责任链"><a href="#19-责任链" class="headerlink" title="19. 责任链"></a>19. 责任链</h2><p>将要做的是组合成一个责任链，让每个对象都有机会执行，参考springMVC的HandlerIterceptor</p>
<p>任务可以所以组合，注意别搞成死循环了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chain</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Handler h1=<span class="keyword">new</span> Handler() &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">boolean</span> <span class="title">doSomething</span><span class="params">(Request req)</span> </span>&#123;</span><br><span class="line">				req.message=req.message+<span class="string">":h1"</span>;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		Handler h2=<span class="keyword">new</span> Handler() &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">boolean</span> <span class="title">doSomething</span><span class="params">(Request req)</span> </span>&#123;</span><br><span class="line">				req.message=req.message+<span class="string">":h2"</span>;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		Handler h3=<span class="keyword">new</span> Handler() &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">boolean</span> <span class="title">doSomething</span><span class="params">(Request req)</span> </span>&#123;</span><br><span class="line">				req.message=req.message+<span class="string">":h3"</span>;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		</span><br><span class="line">		h1.setNext(h2);</span><br><span class="line">		h2.setNext(h3);</span><br><span class="line">		</span><br><span class="line">		Request req=<span class="keyword">new</span> Request();</span><br><span class="line">		req.message=<span class="string">"begin"</span>;</span><br><span class="line">		h1.handle(req);</span><br><span class="line">		</span><br><span class="line">		System.out.println(req.message);</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="20-中介者"><a href="#20-中介者" class="headerlink" title="20. 中介者"></a>20. 中介者</h2><p>当对象之间的交互操作很多且每个对象的行为操作都依赖彼此时，为防止在修改一个对象的行为时，同时涉及很多其他对象的行为，可使用中介者模式。 </p>
<p><img src="/blog/images\20170422200327160.png" alt=""></p>
<h2 id="21-策略模式"><a href="#21-策略模式" class="headerlink" title="21. 策略模式"></a>21. 策略模式</h2><p>流程基本固定，通过给方法传递一个接口，改变计算方式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Strategy</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Method</span></span>&#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invoke</span><span class="params">()</span></span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(Method method)</span> </span>&#123;</span><br><span class="line">		method.invoke();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Method m1=()-&gt;System.out.println(<span class="string">"执行方法1"</span>);</span><br><span class="line">		Method m2=()-&gt;System.out.println(<span class="string">"执行方法2"</span>);</span><br><span class="line">				</span><br><span class="line">		Strategy st=<span class="keyword">new</span> Strategy();</span><br><span class="line">		st.run(m1);</span><br><span class="line">		st.run(m2);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="22-备忘录"><a href="#22-备忘录" class="headerlink" title="22. 备忘录"></a>22. 备忘录</h2><p>将数据在对象外部保存，以便恢复到特定状态</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Memento</span> </span>&#123;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">		String memory;</span><br><span class="line">		Integer age=<span class="number">3</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Person p=<span class="keyword">new</span> Person();</span><br><span class="line">		p.memory=<span class="string">"3岁的记忆"</span>;</span><br><span class="line">		p.age=<span class="number">3</span>;</span><br><span class="line">		<span class="comment">//备份</span></span><br><span class="line">		Map map=<span class="keyword">new</span> HashMap();</span><br><span class="line">		map.put(<span class="string">"age"</span>, p.age);</span><br><span class="line">		map.put(<span class="string">"memory"</span>, p.memory);</span><br><span class="line">		<span class="comment">//删除</span></span><br><span class="line">		p.memory=<span class="string">""</span>;</span><br><span class="line">		p.age=<span class="keyword">null</span>;</span><br><span class="line">		<span class="comment">//恢复</span></span><br><span class="line">		p.memory=(String) map.get(<span class="string">"memory"</span>);</span><br><span class="line">		p.age=(Integer) map.get(<span class="string">"age"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="23-迭代器"><a href="#23-迭代器" class="headerlink" title="23. 迭代器"></a>23. 迭代器</h2><p> 定义：提供一种方法顺序访问一个聚合对象中各个元素，而又不需暴露该对象的内部表示。</p>
<h1 id="模式个人理解"><a href="#模式个人理解" class="headerlink" title="模式个人理解"></a>模式个人理解</h1><h2 id="代理VS装饰器"><a href="#代理VS装饰器" class="headerlink" title="代理VS装饰器"></a>代理VS装饰器</h2><ul>
<li>从语意上讲，代理模式是为控制对被代理对象的访问，而装饰模式是为了增加被装饰对象的功能</li>
<li>代理类所能代理的类完全由代理类确定，装饰类装饰的对象需要根据实际使用时客户端的组合来确定</li>
<li>被代理对象由代理对象创建，客户端甚至不需要知道被代理类的存在；被装饰对象由客户端创建并传给装饰对象</li>
</ul>
<h2 id="策略VS状态VS桥接VS责任链VS命令VS观察者"><a href="#策略VS状态VS桥接VS责任链VS命令VS观察者" class="headerlink" title="策略VS状态VS桥接VS责任链VS命令VS观察者"></a>策略VS状态VS桥接VS责任链VS命令VS观察者</h2><p>考虑以下场景</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> List bs;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">prepare</span><span class="params">(B b)</span> </span>&#123;</span><br><span class="line">		bs.add(b)或bs=b</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(C c)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span>(B impl:list) &#123;</span><br><span class="line">            b.invoke(c)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>有一个主业务类A，它执行un方法之前，会传进来1个或几个B，我们能确定的是客户端在调用run方法前会先调用prepare方法。至于如何调用，调用方式，不同场景会有不同</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">#按顺序</span><br><span class="line">a.prepare(b1)；a.prepare(b2)a.prepare(b3)；a.run(c1)；a.run(c2);</span><br><span class="line">#间隔</span><br><span class="line">a.prepare(b1);a.run(c1);a.prepare(b2);a.run(c2);</span><br><span class="line">#不确定</span><br><span class="line">a.prepare(b1);a.run(c1);a.prepare(b2);a.prepare(b3);a.run(c2);</span><br></pre></td></tr></table></figure>
<p>编码是通常考虑的是：</p>
<ol>
<li>A里存的B是1个还是多个</li>
<li>B的个数是固定的，还是可以任意添加删除</li>
<li>B内部是否要保存状态</li>
<li>不同B的实现类之间需要互相知道彼此吗</li>
<li>不同B之间是否有优先级</li>
<li>参数c是否要在各个b之间传递</li>
<li>是否需要通过调用返回值判断是否继续下一个调用</li>
</ol>
<p>换成设计模式的语言就是这样的:</p>
<div id="flowchart-0" class="flow-chart"></div>



<p><script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/flowchart/1.6.5/flowchart.min.js"></script><textarea id="flowchart-0-code" style="display: none">st=>start: 开始
cond=>condition: B在A中有多个
cond-1=>condition: B由客户端指定
end0=>end: 状态模式
cond0=>condition: B间通信
op0=>operation: B自己确定下个B
op=>operation: B是A的一部分
cond2=>condition: B是简单算法
end1=>end: 策略模式
end2=>end: 桥接
op3=>通常由C主导任务
cond3=>condition: run后移除B
end3=>end: 命令模式
cond4=>condition: B相互独立
end4=>end: 观察者
op5=>operation: C在B间传递
end5=>end: 责任链


st->cond
cond(no,right)->cond-1
cond-1(no,right)->op0->end0
cond-1(yes)->cond2
cond2(yes,right)->end1
cond2(no)->op->end2
cond(yes)->cond3
cond3(yes,right)->end3
cond3(no)->cond4
cond4(yes,right)->end4
cond4(no)->op5
op5->end5</textarea><textarea id="flowchart-0-options" style="display: none">{"scale":1,"line-width":2,"line-length":50,"text-margin":10,"font-size":12}</textarea><script>  var code = document.getElementById("flowchart-0-code").value;  var options = JSON.parse(decodeURIComponent(document.getElementById("flowchart-0-options").value));  var diagram = flowchart.parse(code);  diagram.drawSVG("flowchart-0", options);</script></p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/设计模式/" rel="tag"># 设计模式</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/code/ops/小问题/" rel="next" title="小问题">
                <i class="fa fa-chevron-left"></i> 小问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/code/spring/eureka/develop/eureka-unavailable-replicas/" rel="prev" title="eureka集群unavailable-replicas问题">
                eureka集群unavailable-replicas问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives">
                
                    <span class="site-state-item-count">54</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">25</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">45</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#六大原则"><span class="nav-number">1.</span> <span class="nav-text">六大原则</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#单一职责原则"><span class="nav-number">1.1.</span> <span class="nav-text">单一职责原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#里氏替换原则"><span class="nav-number">1.2.</span> <span class="nav-text">里氏替换原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#接口隔离原则"><span class="nav-number">1.3.</span> <span class="nav-text">接口隔离原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#依赖倒置原则"><span class="nav-number">1.4.</span> <span class="nav-text">依赖倒置原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#迪米特原则"><span class="nav-number">1.5.</span> <span class="nav-text">迪米特原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开-闭原则"><span class="nav-number">1.6.</span> <span class="nav-text">开-闭原则</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建型"><span class="nav-number">2.</span> <span class="nav-text">创建型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-单例"><span class="nav-number">2.1.</span> <span class="nav-text">1. 单例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#错误实现"><span class="nav-number">2.1.1.</span> <span class="nav-text">错误实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#double-check"><span class="nav-number">2.1.2.</span> <span class="nav-text">double check</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#volatile作用"><span class="nav-number">2.1.3.</span> <span class="nav-text">volatile作用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#静态内部类"><span class="nav-number">2.1.4.</span> <span class="nav-text">静态内部类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#恶汉模式"><span class="nav-number">2.1.5.</span> <span class="nav-text">恶汉模式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-静态工厂方法"><span class="nav-number">2.2.</span> <span class="nav-text">2. 静态工厂方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-工厂方法"><span class="nav-number">2.3.</span> <span class="nav-text">3. 工厂方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-抽象工厂"><span class="nav-number">2.4.</span> <span class="nav-text">4. 抽象工厂</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-建造者模式"><span class="nav-number">2.5.</span> <span class="nav-text">5. 建造者模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-原型模式"><span class="nav-number">2.6.</span> <span class="nav-text">6. 原型模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#结构型"><span class="nav-number">3.</span> <span class="nav-text">结构型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-代理模式"><span class="nav-number">3.1.</span> <span class="nav-text">7. 代理模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-适配器"><span class="nav-number">3.2.</span> <span class="nav-text">8. 适配器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-装饰器"><span class="nav-number">3.3.</span> <span class="nav-text">9. 装饰器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-桥接模式"><span class="nav-number">3.4.</span> <span class="nav-text">10.桥接模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-组合模式"><span class="nav-number">3.5.</span> <span class="nav-text">11. 组合模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-享元"><span class="nav-number">3.6.</span> <span class="nav-text">12. 享元</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-门面模式"><span class="nav-number">3.7.</span> <span class="nav-text">13. 门面模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#行为型"><span class="nav-number">4.</span> <span class="nav-text">行为型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#14-观察者"><span class="nav-number">4.1.</span> <span class="nav-text">14. 观察者</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#15-模板方法"><span class="nav-number">4.2.</span> <span class="nav-text">15. 模板方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#16-命令模式"><span class="nav-number">4.3.</span> <span class="nav-text">16. 命令模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#18-状态"><span class="nav-number">4.4.</span> <span class="nav-text">18. 状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#19-责任链"><span class="nav-number">4.5.</span> <span class="nav-text">19. 责任链</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#20-中介者"><span class="nav-number">4.6.</span> <span class="nav-text">20. 中介者</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#21-策略模式"><span class="nav-number">4.7.</span> <span class="nav-text">21. 策略模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#22-备忘录"><span class="nav-number">4.8.</span> <span class="nav-text">22. 备忘录</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#23-迭代器"><span class="nav-number">4.9.</span> <span class="nav-text">23. 迭代器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#模式个人理解"><span class="nav-number">5.</span> <span class="nav-text">模式个人理解</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#代理VS装饰器"><span class="nav-number">5.1.</span> <span class="nav-text">代理VS装饰器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#策略VS状态VS桥接VS责任链VS命令VS观察者"><span class="nav-number">5.2.</span> <span class="nav-text">策略VS状态VS桥接VS责任链VS命令VS观察者</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Pisces</a> v6.3.0</div>





<span id="busuanzi_container_site_uv">
  &nbsp;<span id="busuanzi_value_site_uv"></span>
</span>

<span>/</span>

<span id="busuanzi_container_site_pv">
    <span id="busuanzi_value_site_pv"></span>
</span>


        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.3.0"></script>



  



  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("CIBUz5A0KNFv8xbAPO8ncqk6-gzGzoHsz", "YtGifAKqwENTTs9hhQ1GxdAG");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            
            counter.save(null, {
              success: function(counter) {
                
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.get('time'));
                
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            
              var newcounter = new Counter();
              /* Set ACL */
              var acl = new AV.ACL();
              acl.setPublicReadAccess(true);
              acl.setPublicWriteAccess(true);
              newcounter.setACL(acl);
              /* End Set ACL */
              newcounter.set("title", title);
              newcounter.set("url", url);
              newcounter.set("time", 1);
              newcounter.save(null, {
                success: function(newcounter) {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
                },
                error: function(newcounter, error) {
                  console.log('Failed to create');
                }
              });
            
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  
  

  

  

  

  

  

</body>
</html>
